home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1997 August / Walnut Creek CDROM.7z / LISTINGS / V_12_11 / ALLISON / STR.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1994-09-04  |  1.3 KB  |  64 lines

  1. LISTING 2 - The rest of the string class implementation
  2. // str.cpp
  3. #include <iostream.h>
  4. #include <iomanip.h>
  5. #include <string.h>
  6. #include <assert.h>
  7. #include "str2.h"
  8.  
  9. string& string::operator+=(const string& s2)
  10. {
  11.     if (s2.count > 0)
  12.     {
  13.         size_t new_count = count + s2.count;
  14.         char *buf = new char[new_count + 1];
  15.  
  16.         memcpy(buf,data,count);
  17.         memcpy(buf+count,s2.data,s2.count);
  18.         buf[count = new_count] = '\0';
  19.         delete [] data;
  20.         data = buf;
  21.     }
  22.     return *this;
  23. }
  24.  
  25. string operator+(const string& s1, const string& s2)
  26. {
  27.     string temp(s1);
  28.     return temp += s2;
  29. }
  30.  
  31. int operator==(const string& s1, const string& s2)
  32. {
  33.     return &s1 == &s2 ||
  34.            s1.count == s2.count &&
  35.            strcmp(s1.data,s2.data) == 0;
  36. }
  37.  
  38. ostream& operator<<(ostream& os, const string& s1)
  39. {
  40.     os.write(s1.data,s1.count);
  41.     return os;
  42. }
  43.  
  44. istream& operator>>(istream& is, string& s1)
  45. {
  46.     const size_t BUFSIZ = 256;
  47.     char buf[BUFSIZ];
  48.  
  49.     is.getline(buf,BUFSIZ);
  50.     delete [] s1.data;
  51.     s1.clone(buf);
  52.     return is;
  53. }
  54.  
  55. void string::clone(const char *s)
  56. {
  57.     // Assumes data is deallocated
  58.     assert(s);
  59.     count = strlen(s);
  60.     data = new char[count + 1];
  61.     strcpy(data,s);
  62. }
  63.  
  64.